package com.hot12345.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ReadProperties {

	private static final Log log = LogFactory.getLog(ReadProperties.class);
	
	private static Map<String,Object> keyValues = null;
	
	private static Map<String,Properties> propsMap = new HashMap<String,Properties>();
	private static Map<String,Long> propsSizeMap = new HashMap<String,Long>();//配置文件大小，通过大小判断是否有修改	
	
	//根据key读取value
	public static String readValue(String key) {
		log.debug("dataSource key=" + key);
		
		if(key==null){
			return null;
		}
		
		if(propsMap!=null && propsMap.get("/dataSourceAlias.properties")!=null){
			Properties props = propsMap.get("/dataSourceAlias.properties");
			return (String)props.get(key);
		}
		
		propsMap.put("/dataSourceAlias.properties", null);
		propsSizeMap.put("/dataSourceAlias.properties", null);
		
		loadAllFile();
		Properties props = propsMap.get("/dataSourceAlias.properties");//记住，避免每次都去加载
		if(props==null){
			return null;
		}
		
		return props.getProperty(key);
	 }
	
	//根据key读取value 从system.properties文件
	public static String readValueBySystem(String key) {
		if(key==null){
			return null;
		}
		if(propsMap!=null && propsMap.get("/system.properties") !=null){
			Properties props = propsMap.get("/system.properties");
			return (String)props.get(key);
		}
		log.debug("dataSource key=" + key);
//		Properties props = new Properties();
//		InputStream in = null;
//		String value = null;
//	    try {
//	    	in = ReadProperties.class.getResourceAsStream( "/system.properties");//new BufferedInputStream (new FileInputStream(projectDirectory + "\\src\\config\\" + fileName));
//	    	props.load(in);
//	    	value = props.getProperty(key);
//	    	in.available();
//	    	propsMap.put("/system.properties", props);//记住，避免每次都去加载
//	        log.debug("key=" + key + ",value=" + value);
//	    } catch (Exception e) {
//	    	log.error("Exception",e);
//	    }finally{
//	    	try {
//				in.close();
//			} catch (IOException e) {
//				log.error("IOException",e);
//			}
//	    }
//	    if(value==null){
//	    	value = "";
//	    }
		
		propsMap.put("/system.properties", null);
		propsSizeMap.put("/system.properties", null);
		loadAllFile();
		Properties props = propsMap.get("/system.properties");//记住，避免每次都去加载
		if(props!=null){
			return props.getProperty(key);
		}
	    return null;
	 }
	
	//根据key读取value
	public static String readValue(String filePath,String key) {
		
		if(propsMap!=null && propsMap.get(filePath)!=null){
			Properties props = (Properties)propsMap.get(filePath);
			if(props!=null){
				return (String)props.get(key);
			}
		}
		
		propsMap.put(filePath, null);
		propsSizeMap.put(filePath, null);
		
		loadAllFile();
		Properties props = propsMap.get(filePath);//记住，避免每次都去加载
		if(props==null){
			return null;
		}
		return props.getProperty(key);
	 }
	
	// 根据key读取value
	public static Map<String,Object> readValueAll(String filePath) {
		if(filePath==null){
			return null;
		}
		
		Properties props = null;
		if(propsMap!=null && propsMap.get(filePath)!=null){
			props = (Properties)propsMap.get(filePath);
		} else {
			
			propsMap.put(filePath, null);
			propsSizeMap.put(filePath, null);
			loadAllFile();
			props = propsMap.get(filePath);//记住，避免每次都去加载
		}
		
		log.debug("filePath=" + filePath);
		keyValues = new HashMap<String,Object>();
		if(props!=null){
			Enumeration enums = props.keys();
			while (enums.hasMoreElements()) {
				String key = (String) enums.nextElement();
				log.debug("key = " + key + " value = "
						+ props.get(key));
				keyValues.put(key, props.get(key));
			}
			
			 return keyValues;
		}
		
	    return null;
	 }
	
	@SuppressWarnings("unchecked")
	public static Map readConnectPropertiesToMap(){
		Properties props = new Properties();
		InputStream in = null;
		Map<String,String> map = new HashMap<String,String>();
	    try {
	    	in = ReadProperties.class.getResourceAsStream( "/dataSourceAlias.properties ");//new BufferedInputStream (new FileInputStream(projectDirectory + "\\src\\config\\" + fileName));
	    	 
	    	props.load(in);
	    	map.put("driver",props.getProperty("driver"));
	    	map.put("driverUrl",props.getProperty("driverUrl"));
	    	map.put("user",props.getProperty("user"));
	    	map.put("password",props.getProperty("password"));
	    	map.put("alias",props.getProperty("alias"));
	    	map.put("houseKeepingTestSql",props.getProperty("houseKeepingTestSql"));
	    	map.put("houseKeepingSleepTime",props.getProperty("houseKeepingSleepTime"));
	    	map.put("loginTimeout",props.getProperty("loginTimeout"));
	    	map.put("maximumActiveTime",props.getProperty("maximumActiveTime"));
	    	map.put("minimumConnectionCount",props.getProperty("minimumConnectionCount"));
	    	map.put("maximumConnectionCount",props.getProperty("maximumConnectionCount"));
	    	map.put("maximumConnectionLifetime",props.getProperty("maximumConnectionLifetime"));
	    	map.put("testAfterUse",props.getProperty("testAfterUse"));
	    	map.put("testBeforeUse",props.getProperty("testBeforeUse"));
	    	map.put("trace",props.getProperty("trace"));
	    	map.put("prototypeCount",props.getProperty("prototypeCount"));
	       
	        return map;
	    } catch (Exception e) {
	    	log.error("Exception",e);
	    	return null;
	    }finally{
	    	try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("IOException",e);
			}
	    }
	}

	public static Map<String, Object> getKeyValues() {
		return keyValues;
	}

	public static void setKeyValues(Map<String, Object> keyValues) {
		ReadProperties.keyValues = keyValues;
	}
	
	/**
	 * 加载所有的属性文件，如果有修改，则重新加载。
	 * 
	 * @author wuzongbao
	 * @date 2012-8-6 下午07:08:05
	 */
	public static void loadAllFile(){
		if(propsMap==null){
			log.error("load failure,propsMap==null");
			return;
		}

		
	    for(Map.Entry<String, Properties> entry : propsMap.entrySet()) {
			FileInputStream fin = null;
			
		    try {
		    	String key = null;
		    	if(entry.getKey()!=null){
		    		key = entry.getKey().substring(entry.getKey().lastIndexOf("/")+1, entry.getKey().length());
		    	}
		    	
		    	URL  url = ReadProperties.class.getClassLoader().getResource(key);
		    	if(url==null){
		    		continue;
		    	}
		    	String path = ReadProperties.class.getClassLoader().getResource(key).getPath();
		    	File file = new File(path);
		    	if(file==null){
		    		continue;
		    	}
		    	
		    	//如果属性文件不存在，或者大小相等地，返回。
		    	if(propsSizeMap.get(entry.getKey()) != null && (long)propsSizeMap.get(entry.getKey()) == file.lastModified()){
		    		continue;
		    	}
		    	
		    	fin = new FileInputStream(path);  
		    	Properties props = new Properties();
		    	props.load(fin);
		    	propsMap.put(entry.getKey(), props);
		    	propsSizeMap.put(entry.getKey(), file.lastModified());//记住文件最后修改时间
		    } catch (Exception e) {
		    	log.error("Exception",e);
		    } finally {
		    	if(fin!=null){
			    	try {
						fin.close();
					} catch (IOException e) {
						log.error("IOException",e);
					}
		    	}
		    }
		   
	    }
	}
	
	public static Map<String,Properties> getPropsMap(){
		return propsMap;
	}
}